package com.gomtel.gomtelsdk;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.gomtel.smartdevice.api.BleManager;
import com.gomtel.smartdevice.api.MessageManager;
import com.gomtel.smartdevice.api.bean.BatteryFirmwareVersionResponse;
import com.gomtel.smartdevice.api.bean.BpResponse;
import com.gomtel.smartdevice.api.bean.GoalResponse;
import com.gomtel.smartdevice.api.bean.HistoryEndResponse;
import com.gomtel.smartdevice.api.bean.HrResponse;
import com.gomtel.smartdevice.api.bean.HrvResponse;
import com.gomtel.smartdevice.api.bean.NotificationResponse;
import com.gomtel.smartdevice.api.bean.OrderResponse;
import com.gomtel.smartdevice.api.bean.ProfileBean;
import com.gomtel.smartdevice.api.bean.StepResponse;
import com.gomtel.smartdevice.api.bean.TotalResponse;
import com.gomtel.smartdevice.init.SmartDeviceManager;
import com.gomtel.smartdevice.interfaces.MacUtils;
import com.gomtel.smartdevice.interfaces.OnCallbackListener;
import com.gomtel.smartdevice.interfaces.OnFotaCallbackListener;
import com.gomtel.smartdevice.interfaces.Progress;
import com.kyleduo.switchbutton.SwitchButton;
import com.mediatek.jni.Utils;

import java.io.File;
import java.net.URISyntaxException;

public class MainActivity extends AppCompatActivity {

    Button btn_connect;
    Button btn_verification;
    Button btn_synctime;
    Button btn_bind;
    Button btn_unbind;
    Button btn_getDeviceInfo;
    Button btn_profile;
    Button btn_getHistoryStep;
    Button btn_bp;
    Button btn_fota, btn_hrv, btn_af;
    TextView logView;
    SwitchButton switchTarget, switchPhone, switchSedentary, switchWearing, switchExercise;

    boolean isUnbind = false;
    private static final int FILE_SELECT_CODE = 0;
    public static String MAC = "C3:07:05:A8:05:00";
//                                      "75BCD15"

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SmartDeviceManager.getInstance().init(this);
        MessageManager.getInstance().register();
        btn_connect = (Button) findViewById(R.id.btn_connect);
        btn_verification = (Button) findViewById(R.id.btn_verification);
        btn_synctime = (Button) findViewById(R.id.btn_synctime);
        btn_bind = (Button) findViewById(R.id.btn_bind);
        btn_unbind = (Button) findViewById(R.id.btn_unbind);
        btn_getDeviceInfo = (Button) findViewById(R.id.btn_getDeviceInfo);
        btn_profile = (Button) findViewById(R.id.btn_profile);
        btn_getHistoryStep = (Button) findViewById(R.id.btn_getHistoryStep);
        btn_bp = (Button) findViewById(R.id.btn_bp);
        btn_fota = (Button) findViewById(R.id.btn_fota);
        btn_hrv = (Button) findViewById(R.id.btn_hrv);
        btn_af = (Button) findViewById(R.id.btn_af);

        switchExercise = (SwitchButton) findViewById(R.id.switchExercise);
        switchPhone = (SwitchButton) findViewById(R.id.switchPhone);
        switchSedentary = (SwitchButton) findViewById(R.id.switchSedentary);
        switchTarget = (SwitchButton) findViewById(R.id.switchTarget);
        switchWearing = (SwitchButton) findViewById(R.id.switchWearing);

        logView = (TextView) findViewById(R.id.txt);
        logView.setMovementMethod(ScrollingMovementMethod.getInstance());
        listener();
        getBack();

        openBlue();

    }


    private void openBlue() {
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.isEnabled()) {
            Log.e("tag", " " + Build.MANUFACTURER);
            if (PhoneUtils.isHaiwei()) {

                bluetoothAdapter.disable();
                ToastUtil.showShort(MainActivity.this, "请重启蓝牙");
                bluetoothAdapter.enable();
            }
        } else {
            ToastUtil.showShort(MainActivity.this, "请打开蓝牙");
            bluetoothAdapter.enable();
        }
    }

    public void listener() {
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ScanActivity.class);
                startActivityForResult(intent, 0xa0);

//                BleManager.getInstance().connect(MAC, new OnConnectListener() {
//                    @Override
//                    public void onSuccess() {
//                        ToastUtil.showShort(MainActivity.this, "已连接上");
//                        refreshLogView("已连接上");
//                    }
//
//                    @Override
//                    public void onFailure(Throwable e) {
//                        ToastUtil.showShort(MainActivity.this, "连接失败");
//                        refreshLogView("连接断开");
//                    }
//
//                    @Override
//                    public void onTimeout() {
//                        ToastUtil.showShort(MainActivity.this, "连接超时");
//                        refreshLogView("连接超时");
//                    }
//                });
            }
        });

        btn_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendBind(MacUtils.getMac(MainActivity.this));
            }
        });

        btn_unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isUnbind = true;
                MessageManager.getInstance().sendUnbind(MacUtils.getMac(MainActivity.this));
            }
        });

        btn_verification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendValidation(MacUtils.getMac(MainActivity.this));
            }
        });

        btn_synctime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendTime();
            }
        });

        btn_getDeviceInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendSystemInfo();
            }
        });

        btn_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProfileBean profileBean = new ProfileBean();
                profileBean.setAge(30);
                profileBean.setGender(1);
                profileBean.setHeight(170);
                profileBean.setWeight(58);
                profileBean.setArmLength(73);
                MessageManager.getInstance().sendPersonInfo(profileBean);
            }
        });

        btn_getHistoryStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendHistoryStep();
            }
        });

        btn_bp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendTriggerMeasurement(MessageManager
                        .MeasurementID_BP, MessageManager.MeasurementID_STATUS_START);
            }
        });
        btn_hrv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HrvActivity.class);
                startActivity(intent);
            }
        });

        btn_fota.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });

        btn_af.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, AFActivity.class));
            }
        });

        switchPhone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                MessageManager.getInstance().sendNotification(MessageManager
                                .NOTIFICATION_ID_PHONE_RANG,
                        isChecked ? MessageManager.NOTIFICATION_TURN_ON : MessageManager
                                .NOTIFICATION_TURN_OFF);
            }
        });

        switchWearing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                MessageManager.getInstance().sendNotification(MessageManager
                                .NOTIFICATION_ID_WEARING_LOOSE,
                        isChecked ? MessageManager.NOTIFICATION_TURN_ON : MessageManager
                                .NOTIFICATION_TURN_OFF);
            }
        });

        switchTarget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                MessageManager.getInstance().sendNotification(MessageManager
                                .NOTIFICATION_ID_GOAL_ACHIEVED,
                        isChecked ? MessageManager.NOTIFICATION_TURN_ON : MessageManager
                                .NOTIFICATION_TURN_OFF);
            }
        });


        switchExercise.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                MessageManager.getInstance().sendNotification(MessageManager
                                .NOTIFICATION_ID_EXERCISE,
                        isChecked ? MessageManager.NOTIFICATION_TURN_ON : MessageManager
                                .NOTIFICATION_TURN_OFF);
            }
        });

        switchSedentary.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                MessageManager.getInstance().sendNotification(MessageManager
                                .NOTIFICATION_ID_SEDENTARY,
                        isChecked ? MessageManager.NOTIFICATION_TURN_ON : MessageManager
                                .NOTIFICATION_TURN_OFF);
            }
        });


    }

    public void getBack() {
        MessageManager.getInstance().orderResponse(new OnCallbackListener<OrderResponse>() {
            @Override
            public void onCallback(OrderResponse orderResponse) {
                if (orderResponse.order.equals("D2") && orderResponse.status.equals("00")) {
                    if (isUnbind) {
                        isUnbind = false;
                        BleManager.getInstance().disconnect();
                    }
                }
                refreshLogView("握手回复 ： order = " + orderResponse.order + ", status = " +
                        orderResponse.status);
            }
        });

        MessageManager.getInstance().setBatteryAndFirmwareVersionListener(new OnCallbackListener<BatteryFirmwareVersionResponse>() {
            @Override
            public void onCallback(BatteryFirmwareVersionResponse batteryFirmwareVersionResponse) {
                refreshLogView("Battery = " + batteryFirmwareVersionResponse.getBattery() + ", " +
                        "FirmwareVersion = " + batteryFirmwareVersionResponse.getFirmwareVersion());
            }
        });

        MessageManager.getInstance().setTotalStepListener(new OnCallbackListener<TotalResponse>() {
            @Override
            public void onCallback(TotalResponse totalResponse) {
                refreshLogView("TotalStep = " + totalResponse.getTotalStep() + ", TotalCalories =" +
                        " " + totalResponse.getTotalCalories());
            }
        });

        MessageManager.getInstance().setNotificationListener(new OnCallbackListener<NotificationResponse>() {
            @Override
            public void onCallback(NotificationResponse notificationResponse) {
                refreshLogView("daily = " + notificationResponse.daily + ", sedentary = " +
                        notificationResponse.sedentary +
                        ",wearingLoose = " + notificationResponse.wearingLoose + ", phoneRang = "
                        + notificationResponse.phoneRang +
                        ",exercise = " + notificationResponse.exercise);
            }
        });

        MessageManager.getInstance().setGoalListener(new OnCallbackListener<GoalResponse>() {
            @Override
            public void onCallback(GoalResponse goalResponse) {
                refreshLogView("stepCountGoal = " + goalResponse.getStepCountGoal() + ", " +
                        "heartRateGoal = " + goalResponse.getHeartRateGoal() +
                        ",continue_Time = " + goalResponse.getContinue_Time() + ", duration = " +
                        goalResponse.getDuration() +
                        ",calorie = " + goalResponse.getCalorie());
            }
        });

        MessageManager.getInstance().setProfileListener(new OnCallbackListener<ProfileBean>() {
            @Override
            public void onCallback(ProfileBean profileBean) {
                refreshLogView("age = " + profileBean.getAge() + ", gender = " + profileBean
                        .getGender() +
                        ",height = " + profileBean.getHeight() + ", weight = " + profileBean
                        .getWeight() +
                        ",armLength = " + profileBean.getArmLength());
            }
        });

        MessageManager.getInstance().setStepListener(new OnCallbackListener<StepResponse>() {
            @Override
            public void onCallback(StepResponse stepResponse) {
                refreshLogView("step = " + stepResponse.getTotalStepCount() + ", runStep = " +
                        stepResponse.getRunStepCount() +
                        ",walkDuration = " + stepResponse.getTotalWalkDuration() + ", RunDuration" +
                        " = " + stepResponse.getTotalRunDuration() +
                        ",calorie = " + stepResponse.getCalorie());
            }
        });

        MessageManager.getInstance().setBpListener(new OnCallbackListener<BpResponse>() {
            @Override
            public void onCallback(BpResponse bpResponse) {
                refreshLogView("systolic = " + bpResponse.getSystolic() + ", diastolic = " +
                        bpResponse.getDiastolic() +
                        ",hr = " + bpResponse.getHr() + ", pwtt = " + bpResponse.getPwtt());
            }
        });

        MessageManager.getInstance().setHistoryEndListener(new OnCallbackListener<HistoryEndResponse>() {
            @Override
            public void onCallback(HistoryEndResponse historyEndResponse) {
                refreshLogView("command = " + historyEndResponse.getCommand() + ", featureID = "
                        + historyEndResponse.getFeatureID() +
                        ",response = " + historyEndResponse.getResponse());
            }
        });

        MessageManager.getInstance().setFotaListener(new OnFotaCallbackListener() {
            @Override
            public void onCompleted() {
                refreshLogView("Fota Completed ");

            }

            @Override
            public void onError(Throwable e) {
                refreshLogView("Fota error = " + e.getMessage());
            }

            @Override
            public void onNext(Progress progress) {
                refreshLogView("Fota progress = " + progress.percent);
            }
        });
        MessageManager.getInstance().setNotificationListener(new OnCallbackListener<NotificationResponse>() {
            @Override
            public void onCallback(NotificationResponse notificationResponse) {
                refreshLogView("Notification :    Daily Goal Achieved :" + notificationResponse
                        .isDaily()
                        + "   Sedentary : " + notificationResponse.isSedentary() + "   Wearing " +
                        "Loose : " + notificationResponse.isWearingLoose()
                        + "   Phone Rang :  " + notificationResponse.isPhoneRang() + "   Exercise" +
                        " 30 min  : " + notificationResponse.isExercise());
            }
        });

        MessageManager.getInstance().setHrvListener(new OnCallbackListener<HrvResponse>() {
            @Override
            public void onCallback(HrvResponse hrvResponse) {
                refreshLogView("Hrv :   hf = " + hrvResponse.getHF() + "  lf = " + hrvResponse
                        .getLF()
                        + "  hf_lf = " + hrvResponse.getLF_HF() + "   hr = " + hrvResponse.getHr()
                        + "  sdnn = " + hrvResponse.getSDNN());

                int mAge = 30; //设置的年龄,这里为了方便直接使用默认值
                int pressure = Utils.get_pressure_index_from_sdnn(hrvResponse.getSDNN() / 1000,
                        mAge);
                int fatigue = Utils.get_fatigue_index_from_hrv(hrvResponse.getLF() / 1000,
                        hrvResponse.getHF() / 1000);
                /**
                 *  hrvState = 0 : 正常
                 *             1 : 兴奋
                 *             2 : 良好
                 *             3 : 焦虑
                 *             4 : 抑郁
                 */
                int hrvState = Utils.getHrvState(mAge, hrvResponse.getSDNN(), hrvResponse.getHr());
                int estAge = Utils.getEstAge(mAge, hrvResponse.getSDNN(), hrvResponse.getHr());
                refreshLogView("Hrv :   压力指数= " + pressure + "  疲劳指数 = " + fatigue
                        + "  hrv状态 = " + hrvState + "   心理年龄 = " + estAge);
            }
        });
        MessageManager.getInstance().setHeartRateListener(new OnCallbackListener<HrResponse>() {
            @Override
            public void onCallback(HrResponse hrResponse) {
                refreshLogView("Hr = " + hrResponse.hr + "  time:" + hrResponse.unixTimestamp);
            }
        });
    }

    public void refreshLogView(String msg) {
        logView.append("\n-----------------------------");
        logView.append("\n" + msg);
        int offset = logView.getLineCount() * logView.getLineHeight();
        if (offset > logView.getHeight()) {
            logView.scrollTo(0, offset - logView.getHeight());
        }
    }

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"),
                    FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    private static final String TAG = "ChooseFile";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = data.getData();
                        String path = FileUtils.getPath(this, uri);
                        Log.d(TAG, "File Path: " + path);
                        File file = new File(path);
                        MessageManager.getInstance().startFota(file, MAC);
                    } catch (URISyntaxException e) {
                    }
                }
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().disconnect();
        MessageManager.getInstance().unRegister();
    }


}
